﻿using DocumentFormat.OpenXml.Spreadsheet;
using DotNetCore.CAP;
using Magicodes.ExporterAndImporter.Excel;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using MT.Enterprise.Utils.Extensions;
using NP.BPMReportPlatform.DBHelper;
using NP.BPMReportPlatform.Entities.BPM_Business;
using NP.BPMReportPlatform.Entities.BPM_Platform;
using NP.BPMReportPlatform.Leave;
using NP.BPMReportPlatform.Leave.Dto;
using NP.BPMReportPlatform.RecurringJobs.Dto;
using NP.BPMReportPlatform.SF.Dto;
using NP.Enterprise.Utils.HanaOdbc;
using NP.Enterprise.Utils.Http;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using OfficeOpenXml.Drawing.Chart;
using Serilog;
using Serilog.Core;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Net.Mail;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Application.Dtos;

namespace NP.BPMReportPlatform.RecurringJobs
{
    public class LeaveSyncJob : BpmReportPlatformRecurringJob, ILeaveSyncJob
    {
        private readonly SqlSugarClient _db, _dbPlatform;
        private readonly ILogger _logger;
        private IHostingEnvironment _env;
        private readonly IConfiguration _configuration;
        private readonly INPRestHttpHelper _nPRestHttp;
        private readonly ILeaveService _leaveService;

        public LeaveSyncJob(ISqlSugarAppService sqlSugarAppService,
            IConfiguration configuration,
            ILogger logger,
            IHostingEnvironment env,
            INPRestHttpHelper nPRestHttp,
            ILeaveService leaveService)
        {
            _db = sqlSugarAppService.GetBusinessInstance();
            _dbPlatform = sqlSugarAppService.GetPlatformInstance();
            _logger = logger;
            _env = env;
            _configuration = configuration;
            _nPRestHttp = nPRestHttp;
            _leaveService = leaveService;
        }

        public async Task DoSyncWork()
        {
            try
            {
                await ReSyncFailedLeaveData();
            }
            catch(Exception ex)
            {
                _logger.Error($"LeaveSyncJob DoSyncWork Error：{ex}");
            }
        }

        public async Task DoSnendEmailWork()
        {
            try
            {
                await SendSyncFailedEmail();
            }
            catch (Exception ex)
            {
                _logger.Error($"LeaveSyncJob DoSnendEmailWork Error：{ex}");
            }
        }

        /// <summary>
        /// 每天7点执行
        /// </summary>
        /// <returns></returns>
        public async Task ReSyncFailedLeaveData()
        {
            _logger.Information($"ReSyncFailedLeaveData Start");

            DateTime startTime = DateTime.Today.ToString("yyyy-MM-dd 00:00:00").ToOurDateTime().AddMonths(-1);
            DateTime endTime = DateTime.Today.ToString("yyyy-MM-dd 23:59:59").ToOurDateTime();

            // 获取审批通过且推送失败的数据
            var leaveDatas = await _db.Queryable<LeaveEntity, LeaveDetailEntity, BusinessProcessesNew>(
                (x, l, b) => x.Id == l.LeaveId && x.InstanceNumber == b.InstanceId)
                .Where((x, l, b) => x.Status == 2 && x.PushStatus == -1 && b.FinishTime <= endTime && b.FinishTime >= startTime)
                .Select(x => new
                {
                    x.InstanceNumber,
                }).Distinct().ToListAsync();
            foreach (var leaveData in leaveDatas)
            {
                await _leaveService.PushSAPAsync(leaveData.InstanceNumber, "leave");
                await Task.Delay(500);
            }

            var leaveCancelDatas = await _db.Queryable<LeaveCancelEntity, LeaveCancelDetailEntity, BusinessProcessesNew>(
                (x, l, b) => x.Id == l.LeaveCancelId && x.InstanceNumber == b.InstanceId)
                .Where((x, l, b) => x.Status == 2 && x.PushStatus == -1 && b.FinishTime <= endTime && b.FinishTime >= startTime)
                .Select(x => new
                {
                    x.InstanceNumber,
                }).Distinct().ToListAsync();
            foreach (var leaveCancelData in leaveCancelDatas)
            {
                await _leaveService.PushSAPAsync(leaveCancelData.InstanceNumber, "cancelleave");
                await Task.Delay(500);
            }

            _logger.Information($"ReSyncFailedLeaveData End");
        }

        /// <summary>
        /// 每天9点发送
        /// </summary>
        /// <returns></returns>
        public async Task SendSyncFailedEmail()
        {
            _logger.Information($"SendSyncFailedEmail Start");
            await _nPRestHttp.PostAsync($"{_configuration["BPM:BusinessApiUrl"]}leaveManage/SendSyncFailedEmail", null);
        }
    }
}
